package com.zzr.demo.rabbitmq.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.annotation.PostConstruct;

/**
 * @author: xiaomi
 * @date: 2021/8/25
 * @description: 可靠投递：
 * A:Broker 确认
 * B:Consumer 确认
 */
@Configuration
@Slf4j
public class MyRabbitConfig {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //    @Primary
//    @Bean
    @PostConstruct
    public RabbitTemplate rabbitTemplate() {
        //RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        //this.rabbitTemplate = rabbitTemplate;
        //需要设置这个，否则失败投递的消息会被丢弃！
//        rabbitTemplate.setMandatory(true);
//        rabbitTemplate.setMandatory(determineMandatoryFlag(properties));
        rabbitTemplate.setMessageConverter(messageConverter());
        //回调机制
        initRabbitTemplate();
        return rabbitTemplate;
    }


    /**
     * A:Broker 确认
     * 设置消息 可靠投递
     * 没有设置时，以下投递失败：
     * 1.投递到 exchange 失败：只会打印 Error 日志；
     * 2.投递到 queue 失败：没有任何反馈；
     * 进行以下设置后：
     */
    private void initRabbitTemplate() {

        /**
         * 设置确认回调
         */
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {

            /**
             *
             * @param correlationData   当前消息的唯一关联数据(这个是消息的唯一id)
             * @param b 消息是否成功收到(只要消息抵达 Broker => true)
             * @param s 失败的原因
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean b, String s) {
                log.info("confirm.correlationData:{},ack:{},cause:{}", correlationData, b, s);
            }
        });

        /**
         * 1.路由键失败；
         * 2.集群模式下，不是所有节点的队列收到消息
         */
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            /**
             * 只要消息没有投递给指定的队列，就触发这个失败回调
             * @param message   投递失败的消息详细信息
             * @param replyCode 回复的状态码
             * @param replyText 回复的文本内容
             * @param exchange  当时这个消息发给哪个交换机
             * @param routingKey    当时这个消息用哪个路邮键
             */
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                log.info("Fail Message:{}.replyCode:{},replyText:{},exchange:{},routingKey:{}", message, replyCode, replyText, exchange, routingKey);
            }
        });

//        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
//            System.out.println("Fail Message[" + message + "]==>replyCode[" + replyCode + "]" +
//                    "==>replyText[" + replyText + "]==>exchange[" + exchange + "]==>routingKey[" + routingKey + "]");
//        });

    }

    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    //region private methods

    private boolean determineMandatoryFlag(RabbitProperties properties) {
        Boolean mandatory = properties.getTemplate().getMandatory();
        return (mandatory != null) ? mandatory : properties.isPublisherReturns();
    }
    //endregion


}
